#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
K717路径生成调试脚本
显示每个线段是直线(L)还是弧线(A)
"""

def debug_k717_path_generation():
    """调试K717的顶点路径生成，显示每个线段类型"""
    
    # 读取K717文件
    with open('test-data/1KA-ARCH-P-R-K717.txt', 'r', encoding='utf-8') as f:
        content = f.read()
    
    print("=== K717顶点路径生成调试 ===")
    
    # 使用现有的解析器解析
    from ploop_processor_fixed import PLoopProcessor
    processor = PLoopProcessor()
    ploops = processor.parse_file(content)
    
    if not ploops:
        print("❌ 没有找到PLOOP数据")
        return
    
    ploop = ploops[0]  # K717
    print(f"\n📊 PLOOP信息:")
    print(f"  名称: {ploop.name}")
    print(f"  高度: {ploop.height}mm")
    print(f"  原始顶点数: {len(ploop.vertices)}")
    
    # 进行PLOOP处理（FRADIUS信息已经在处理过程中保留）
    final_vertices = processor.process_ploop(ploop)
    print(f"  PLOOP处理后顶点数: {len(final_vertices)}")

    # 检查FRADIUS信息
    fradius_count = sum(1 for v in final_vertices if hasattr(v, 'fradius') and v.fradius and v.fradius > 0)
    print(f"  处理后包含FRADIUS的顶点数: {fradius_count}")

    # 查找顶点19并应用分割点逻辑
    vertex_19_index = None
    for i, v in enumerate(final_vertices):
        if abs(v.x - 400.0) <= processor.tolerance and abs(v.y) <= processor.tolerance:
            vertex_19_index = i
            break

    is_open_path = False

    if vertex_19_index is not None:
        print(f"\n🎯 发现顶点19在索引{vertex_19_index}: ({final_vertices[vertex_19_index].x:.2f}, {final_vertices[vertex_19_index].y:.2f})")

        # 检查顶点19是否是最后一个顶点，如果是，说明需要截断回到起点的线段
        if vertex_19_index == len(final_vertices) - 1:
            # 顶点19是最后一个顶点，检查是否需要截断回到起点的线段
            first_vertex = final_vertices[0]
            distance_to_start = ((first_vertex.x - final_vertices[vertex_19_index].x)**2 +
                               (first_vertex.y - final_vertices[vertex_19_index].y)**2)**0.5

            if (distance_to_start < 1000 and
                abs(final_vertices[vertex_19_index].y) <= processor.tolerance and
                abs(first_vertex.y) <= processor.tolerance):
                print(f"  ✅ 检测到顶点19到起点的短线（{distance_to_start:.2f}mm），需要截断")
                print(f"  ✅ 设置为开放路径，在顶点19处结束")
                is_open_path = True
        elif vertex_19_index < len(final_vertices) - 1:
            # 顶点19不是最后一个顶点，检查右边的线段
            next_vertex = final_vertices[vertex_19_index + 1]
            distance_to_next = ((next_vertex.x - final_vertices[vertex_19_index].x)**2 +
                              (next_vertex.y - final_vertices[vertex_19_index].y)**2)**0.5

            if (distance_to_next < 1000 and
                abs(final_vertices[vertex_19_index].y) <= processor.tolerance and
                abs(next_vertex.y) <= processor.tolerance):
                print(f"  ✅ 检测到顶点19右边的短线（{distance_to_next:.2f}mm），需要截断")
                final_vertices = final_vertices[:vertex_19_index + 1]
                is_open_path = True
    
    print(f"\n📍 最终顶点列表 ({len(final_vertices)}个顶点):")
    for i, v in enumerate(final_vertices):
        has_fradius = hasattr(v, 'fradius') and v.fradius and v.fradius > 0
        frad_info = f", FRAD:{v.fradius:.2f}" if has_fradius else ""
        print(f"  [{i:2d}] ({v.x:8.2f}, {v.y:8.2f}, {v.z:8.2f}){frad_info}")

    # 显示FRADIUS映射详情
    print(f"\n🔍 FRADIUS映射详情:")
    fradius_vertices = [v for v in final_vertices if hasattr(v, 'fradius') and v.fradius and v.fradius > 0]
    if fradius_vertices:
        for i, v in enumerate(final_vertices):
            if hasattr(v, 'fradius') and v.fradius and v.fradius > 0:
                print(f"  顶点[{i}]: ({v.x:.2f}, {v.y:.2f}) - FRADIUS: {v.fradius:.2f}mm")
    else:
        print(f"  ❌ 没有找到FRADIUS信息，检查映射过程")
    
    # 生成路径表达
    print(f"\n🛤️  顶点路径表达:")
    print(f"路径类型: {'开放路径' if is_open_path else '闭合路径'}")
    print(f"起点: 顶点0 ({final_vertices[0].x:.2f}, {final_vertices[0].y:.2f})")
    
    for i in range(len(final_vertices) - 1):
        current_vertex = final_vertices[i]
        next_vertex = final_vertices[i + 1]
        
        # 检查当前顶点是否有FRADIUS
        has_fradius = hasattr(current_vertex, 'fradius') and current_vertex.fradius and current_vertex.fradius > 0
        if has_fradius:
            # 这是一个圆弧的起点
            print(f"  {i:2d}(A)->{i+1:2d}  弧线: ({current_vertex.x:8.2f}, {current_vertex.y:8.2f}) → ({next_vertex.x:8.2f}, {next_vertex.y:8.2f}) [R{current_vertex.fradius:.0f}]")
        else:
            # 这是一条直线
            distance = ((next_vertex.x - current_vertex.x)**2 + (next_vertex.y - current_vertex.y)**2)**0.5
            print(f"  {i:2d}(L)->{i+1:2d}  直线: ({current_vertex.x:8.2f}, {current_vertex.y:8.2f}) → ({next_vertex.x:8.2f}, {next_vertex.y:8.2f}) [距离:{distance:.2f}mm]")
    
    if not is_open_path:
        # 闭合路径需要从最后一个顶点回到起点
        last_vertex = final_vertices[-1]
        first_vertex = final_vertices[0]
        distance = ((first_vertex.x - last_vertex.x)**2 + (first_vertex.y - last_vertex.y)**2)**0.5
        print(f"  {len(final_vertices)-1:2d}(L)->0   直线: ({last_vertex.x:8.2f}, {last_vertex.y:8.2f}) → ({first_vertex.x:8.2f}, {first_vertex.y:8.2f}) [距离:{distance:.2f}mm] (闭合)")
    
    print(f"\n终点: 顶点{len(final_vertices)-1} ({final_vertices[-1].x:.2f}, {final_vertices[-1].y:.2f})")
    
    # 统计信息
    line_count = 0
    arc_count = 0
    for i in range(len(final_vertices) - 1):
        has_fradius = hasattr(final_vertices[i], 'fradius') and final_vertices[i].fradius and final_vertices[i].fradius > 0
        if has_fradius:
            arc_count += 1
        else:
            line_count += 1
    
    if not is_open_path:
        line_count += 1  # 闭合线段
    
    print(f"\n📊 路径统计:")
    print(f"  直线段数: {line_count}")
    print(f"  弧线段数: {arc_count}")
    print(f"  总线段数: {line_count + arc_count}")
    print(f"  路径状态: {'开放' if is_open_path else '闭合'}")
    
    return final_vertices, is_open_path

if __name__ == "__main__":
    debug_k717_path_generation()
